package com.lagou.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class MySqlConn {
    //获取ZlClient对象
    public static ZkClient zkClient = new ZkClient("192.168.20.101:2181,192.168.20.100:2181,192.168.20.102:2181");
    public static Map<String, Object> jdbcParamData = new HashMap();
    public static DruidDataSource conn_pool = JDBCConnPool.druidDataSource;

    private static void getParam() {
        Object readData = zkClient.readData("/jdbc");
        System.out.println("获取节点信息" + readData.toString());
        String[] splits = readData.toString().split(",");
        for (String str : splits) {
            int i = str.indexOf("=");
            String key = str.substring(0, i);
            String value = str.substring(i + 1);
            System.out.println("key=" + key + ", value=" + value);
            jdbcParamData.put(key, value);
        }
        System.out.println(jdbcParamData.toString());
    }

    private static void getParam(Object o) {
        System.out.println("节点变更信息：" + o.toString());
        String[] splits = o.toString().split(",");
        for (String str : splits) {
            int i = str.indexOf("=");
            String key = str.substring(0, i);
            String value = str.substring(i + 1);
            System.out.println("key=" + key + ", value=" + value);
            jdbcParamData.put(key, value);
        }
        System.out.println(jdbcParamData.toString());
    }

    public static Connection newConnection() {
        if (jdbcParamData.isEmpty()) {
            System.out.println("*****数据库参数为空，从zookeeper配置中心路径/jdbc节点获取获取配置参数*****");
            getParam();
            System.out.println("=========================参数获取完成！！！==========================");
        }
        try {
            System.out.println(jdbcParamData.get("url").toString());
            Connection conn = JDBCConnPool.getConnection(jdbcParamData.get("url").toString(),
                    jdbcParamData.get("driverClassName").toString(),
                    jdbcParamData.get("username").toString(),
                    jdbcParamData.get("password").toString(),
                    Integer.parseInt(jdbcParamData.get("initialSize").toString()),
                    Integer.parseInt(jdbcParamData.get("maxActive").toString()),
                    Integer.parseInt(jdbcParamData.get("maxWait").toString()));
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void run() throws InterruptedException {

        //序列化
        zkClient.setZkSerializer(new zkStrSerializer());
        //注册监听数据变化

        zkClient.subscribeDataChanges("/jdbc", new IZkDataListener() {
            //监听数据变化
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println("数据库配置数据发生改变！");
                if (conn_pool.isInited()) {
                    System.out.println("+++++++++++++已经初始化，关闭连接池并重启+++++++++++++++");
                    //释放旧的连接池资源
                    conn_pool.close();
                    //重启连接池
                    conn_pool.restart();
                    //获取新的资源池链接数据
                    getParam(o);
                } else {
                    System.out.println("=============未初始化,无需重启连接池=========");
//                    newConnection();
//                    conn_pool.init();
                }
            }

            public void handleDataDeleted(String s) throws Exception {
                System.out.println("节点" + s + "被删除！！！");
            }
        });
    }
}
